const Dramas = require("../models/Dramas")
const fs = require("fs")


const addOneDrama = async (query) => {
    try {
        const dramasaved = await Dramas(query).save()
        return dramasaved;
    }
    catch (err) {
        throw Error(err);
    }
}

const removeOneDrama = async (_id) => {
    try {
        console.log(_id)
        const dramaremoved = await Dramas.findByIdAndRemove(_id)
        return dramaremoved;
    }
    catch (err) {
        throw Error(err);
    }
}

const updateOneDrama = async (_id, column, content) => {
    try {
        var flag;
        const dramafound = await Dramas.findById(_id)
        
        for (item in dramafound._doc) {
            if (item == column) {
                flag = 1;
            }
        }
        if (flag) {
            try {
                dramafound[column] = content;
                console.log(dramafound)
                await dramafound.save();
                
                return dramafound;
            }
            catch (err) {
                console.log(err)
                return 2;
            }

        } else {
            return 1;
        }
    }
    catch (err) {
        return null;
    }
}

const findDrama = async (content) => {
    try {
        const dramafound = await Dramas.find({ name: eval("/" + content + "/i") }).limit(10)

        return dramafound;
    }
    catch (err) {
        throw Error(err);
    }
}

const findDramaByTag = async (content) => {
    try {
        const dramafound = await Dramas.find({ tags: eval("/" + content + "/i") }).limit(10)

        return dramafound;
    }
    catch (err) {
        throw Error(err);
    }
}


const deleteFile = async (_id, column) => {
    const dramafound = await Dramas.findById(_id)
    const fileDIR = dramafound[column]
    try{
        var reg = /\/public.*/
        var DIR = "." + fileDIR.match(reg)[0]
        if (fs.existsSync(DIR)) {
            fs.unlink(DIR, (err) => {
                if(err){
                    console.log(err)
                }
            })
        }
    }
    catch (err) {
        return
    }
    


}


module.exports = { addOneDrama, removeOneDrama, updateOneDrama, findDrama, deleteFile,findDramaByTag }

